/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jsf;
import ejb.Warehouse;
import ejb.Company;
import bean.WarehouseBean;
import bean.CompanyBean;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
/**
 *
 * @author longdm
 */

public class WarehouseController {

    /** Creates a new instance of WarehouseController */
    public WarehouseController() {
        warehouseDataModel = new ListDataModel();
    }

    private Warehouse currentWarehouse;
    private ListDataModel warehouseDataModel;

    public Warehouse getCurrentWarehouse() {
        return currentWarehouse;
    }

    public ListDataModel getWarehouseDataModel() {
        WarehouseBean wb = new WarehouseBean();
        warehouseDataModel.setWrappedData(wb.getAllWarehouse());
        return warehouseDataModel;
    }

    public String newWarehouse()
    {
        WarehouseBean wb = new WarehouseBean();
        wb.createWarehouse(currentWarehouse);
        return "warehouseManager";
    }

    public String updateWarehouse()
    {
        WarehouseBean wb = new WarehouseBean();
        wb.editWarehouse(currentWarehouse);
        return "warehouseManager";
    }

    public String deleteWarehouse()
    {
        currentWarehouse = (Warehouse) warehouseDataModel.getRowData();
        if(currentWarehouse.getProductCollection().size()==0)
        {
            WarehouseBean wb = new WarehouseBean();
            wb.removeWarehouse(currentWarehouse);
        }
        else
        {
            FacesMessage mes = new FacesMessage("cannot delete", "There are somethings contains");
            mes.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage("delete_error", mes);
        }
        return "";
    }

    public String toWarehouseEdit()
    {
        currentWarehouse = (Warehouse) warehouseDataModel.getRowData();
        return "warehouseEdit";
    }

    public String toNewWarehouse()
    {
        currentWarehouse = new Warehouse();
        return "newWarehouse";
    }

    public SelectItem[] getCompanySelectItems()
    {
        CompanyBean cb = new CompanyBean();
        List<Company> coms = cb.getAllCompany();

        SelectItem[] items = new SelectItem[coms.size()];
        int i = 0;

        for(Company c : coms)
        {
            items[i] = new SelectItem(c,c.getCompanyName());
            i++;
        }
        return items;
    }
}
